package com.pdf.editor;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.input.ZoomEvent;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

public class MainController {

    @FXML
    public Button decryptBtn;

    @FXML
    public TextField filePath;

    @FXML
    public TabPane tabPane;

    private File file;

    private Stage stage;
    private Scene scene;

    private final FXMLLoader decode_dialog_loader = new FXMLLoader(MainController.class.getResource("decrypt-dialog.fxml"));

    /*@FXML
    public void initialize() {
        this.decode_dialog_loader = new FXMLLoader(MainController.class.getResource("decrypt-dialog.fxml"));
        try {
            this.decode_dialog_loader.load();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
*/
    public void init(Scene scene) {
        this.scene = scene;

        this.scene.widthProperty().addListener((observable, oldV, newV) -> {
            tabPane.setPrefWidth(newV.doubleValue());
        });

        this.scene.heightProperty().addListener((observable, oldV, newV) -> {
            tabPane.setPrefHeight(newV.doubleValue());
        });
    }

    /**
     * 打开文件选择器
     */
    @FXML
    protected void choseFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");
        fileChooser.setInitialDirectory(new File("/"));
        File file = fileChooser.showOpenDialog(this.stage);

        if (Objects.nonNull(file)) {
            filePath.setText(file.getAbsolutePath());
            this.file = file;
            tabPane.getTabs().add(new PDFTab(file.getName(), file));
        }
    }

    /**
     * PDF解密
     */
    @FXML
    protected void onDecryptBtnClick() throws IOException {
        if (Objects.isNull(file)) {
            return;
        }

        if (Objects.isNull(this.stage)) {
            Scene scene = new Scene(decode_dialog_loader.load(), 350, 100);
            Stage stage = new Stage();
            stage.setScene(scene);
            stage.setResizable(false);
            stage.setTitle("PDF密码");
            this.stage = stage;
        }

        DecryptDialogController decryptDialogController = decode_dialog_loader.getController();
        decryptDialogController.setFile(this.file);
        decryptDialogController.tips.setText("");

        this.stage.show();
    }

    public void onZoom(ZoomEvent zoomEvent) {
        System.out.println(zoomEvent);
    }
}